<template>
	<view :id="templateId" v-if="loaded" class="container">
		<view :style="themeStyles.btnFullColor" class="status-wrap">
			<!-- 状态区域 begin -->
			<view class="status-content">
				<uni-icon
					:color="themeStyles.auxiliaryColor"
					:name="viewStatusIcon(orderInfo.status)"
					size="64rpx"
				>
				</uni-icon>
				<view class="df1 content">
					<view class="title">{{ orderInfo.statusValue }}</view>
					<view v-if="orderInfo.statusTitle" class="desc">{{
						orderInfo.statusTitle
					}}</view>
				</view>
			</view>
			<!-- 状态区域 end -->
		</view>
		<!-- 地址 -->
		<!-- 快递 or 到店 or 付款码支付 -->
		<view 
			v-if="orderInfo.type!='20'"
			class="page-panel address-section">
			<!-- 物流信息??? &&orderInfo.logisticsTime -->
			<view 
				v-if="orderInfo.type=='10'&&(orderInfo.status=='300'||orderInfo.status=='400')" 
				class="logistics-content"
				@click.stop="queryLogistisc(orderInfo.logisticsNo)">
				<uni-icon
					:color="themeStyles.adronmentColor"
					name="car-full"
					size="60rpx"
				>
				</uni-icon>
				<view class="cen">
					<view
						:style="themeStyles.textAdronmentColor"
						class="logistics-desc"
						>{{ orderInfo.logisticsMessage }}</view
					>
					<text class="logistics-date">{{
						orderInfo.logisticsTime
					}}</text>
				</view>
				<!--  -->
				<uni-icon
					name="right"
					size="36rpx"
				></uni-icon>
			</view>
			<!-- 客户地址 or 门店地址 -->
			<view class="address-content">
				<uni-icon
					:color="themeStyles.lightMainColor"
					name="address-full"
					size="60rpx"
				>
				</uni-icon>
				<!-- 线上订单 -->
				<view
					v-if="orderInfo.type=='10'" 
					class="cen">
					<view class="top">
						<text class="name">{{ orderInfo.customerName }}</text>
						<text class="mobile">{{
							orderInfo.customerPhone
						}}</text>
					</view>
					<text class="address">{{
						orderInfo.customerAddress || ""
					}}</text>
				</view>
				<!-- 到店自取 -->
				<view
					v-if="orderInfo.type=='15'" 
					class="cen">
					<view class="top">
						<text class="name">{{ '门店地址' }}</text>
					</view>
					<text class="address">{{shopDetailInfo.address}}</text>
				</view>
				<!-- <uni-icon
					v-if="orderInfo.type=='10'"
					name="right"
					size="36rpx"
				></uni-icon> -->
			</view>
		</view>
		<!--  -->
		<view 
			class="goods-section">
			<!-- 商品列表 -->
			<view class="goods-list">
				<view
					v-for="(item, index) in orderInfo.orderGoodsList"
					:key="index"
					class="goods-item"
				>
					<uni-goods-col
						:goods="item"
						:goodsTypeText="item.skuName"
						:routeLink="
							`/pages/common/pages/goods/goodsDetail?goodsId=${item.goodsId}`
						"
						:goodsPrice="item.priceStr.split('.')"
						:latePrice="item.priceOut"
					>
						<view slot="metaRight">
							<view class="cut-num">x{{ item.buyNumber }}</view>
						</view>
					</uni-goods-col>
					<view
						v-if="item.refundsStatus !== 50"
						class="df jc-fe ertra-btn"
					>
						<button
							v-if="item.refundsStatus === 0&&orderInfo.type==10"
							@click.stop="separateRefunds(item)"
							class="df df-r btn"
						>
							退款
						</button>
						<text
							v-else-if="item.refundsStatus === 100"
							class="df df-r btn btn-plain"
							>已售后</text
						>
						<text
							v-else-if="item.refundsStatus === 75"
							class="df df-r btn btn-plain"
							>售后中</text
						>
					</view>
				</view>
			</view>
		</view>

		<!-- 金额明细 -->
		<view class="price-section">
			<view class="yt-list">
				<view class="df jc-sb yt-list-cell">
					<text class="cell-tit clamp">订单号</text>
					<text class="cell-right">{{ orderInfo.orderId }}</text>
				</view>
				<view
					v-if="orderInfo.couponRemission > 0"
					class="df jc-sb yt-list-cell"
				>
					<text class="cell-tit clamp">优惠券</text>
					<text class="cell-right"
						>优惠￥{{ orderInfo.couponRemission || 0 }}</text
					>
				</view>
				<view
					v-if="orderInfo.memberRemission > 0"
					class="df jc-sb yt-list-cell"
				>
					<text class="cell-tit clamp">会员</text>
					<text class="cell-right"
						>优惠￥{{ orderInfo.memberRemission }}</text
					>
				</view>
				<view
					v-if="orderInfo.type=='10'" 
					class="df jc-sb yt-list-cell">
					<text class="cell-tit clamp">运费</text>
					<text class="cell-right">{{
						orderInfo.freight > 0
							? "￥" + orderInfo.freight
							: "快递免邮"
					}}</text>
				</view>
				<view class="df jc-fe ai-fe real-price-box">
					<text class="title">实付金额：</text>
					<view :style="themeStyles.textMainColor" class="price-box">
						<text class="price">{{ orderInfo.totalFee[0] }}</text>
						<text class="decimal">{{
							orderInfo.totalFee[1] || "00"
						}}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部 -->
		<view class="df jc-fe footer">
			<view class="footer-box">
				<view class="btn-group">
					<button
						v-if="showBatchBtn&&orderInfo.type==10"
						@click="batchRefunds()"
						type="primary"
						class="df df-c btn"
					>
						批量退款
					</button>
					<button
						v-if="viewBtn(orderInfo.status, 1, orderInfo.type)"
						@click.stop="queryLogistisc(orderInfo.logisticsNo)"
						type="primary"
						class="df df-c btn"
					>
						查看物流
					</button>
					<button
						v-if="viewBtn(orderInfo.status, 2, orderInfo.type)"
						@click="onCancelOrder(orderInfo.orderId)"
						type="primary"
						class="df df-c btn"
					>
						取消订单
					</button>
					<button
						v-if="viewBtn(orderInfo.status, 4, orderInfo.type)"
						@click="onDeleteOrder(orderInfo.orderId)"
						type="primary"
						class="df df-c btn"
					>
						删除订单
					</button>
					<!-- 主按钮 begin -->
					<button
						v-if="!!statusPrompt.submitBtnText"
						type="primary"
						:style="themeStyles.btnFullColor"
						class="df df-c btn full"
						@click="onFullSubmit()"
					>
						{{ statusPrompt.submitBtnText }}
					</button>
					<!-- 主按钮 end -->
				</view>
			</view>
		</view>
		<!-- 选择支付方式弹层 -->
		<pop-pay
			:type="orderInfo.type"
			:showPopPay="showPopPay"
			:orderInfo="orderInfo"
			@close="closePopPay"
			@select-pay-type="selectPayMoneyTypeAfter"
			@payBefore="callPayBefore"
			@payFn="callPay"
			@paySuccessAfter="paySuccessAfter"
			@payFailAfter="payFailAfter"></pop-pay>
	</view>
</template>

<script>
/** api begin */
import { queryDefaultAddress } from "@/lib/api/customerServer/address";

import {
	queryOrderDetail,
	updateOrderAddrFromApp
} from "@/lib/api/orderServer/order";

import { baseFileUri } from "@/utils/request/baseConfig";
/** api end */

/** components begin */
import uniCountdown from "@/components/uniCountdown/uniCountdown";
import uniGoodsCol from "@/components/goods/uniGoodsCol";
import uniIcon from "@/components/uniIcon/uniIcon";
/* 选择支付方式弹层 */
import popPay from "@/components/popPay";
/** components end */

/** minxins begin */
import orderMixin from "@/mixins/order/order";
import payMixin from "@/mixins/pay";
/** minxins end */

import { mapState, mapMutations } from "vuex";
export default {
	mixins: [orderMixin, payMixin],
	components: {
		uniCountdown,
		uniGoodsCol,
		uniIcon,
		popPay
	},

	data() {
		return {
			statusPrompt: {
				title: "",
				desc: "",
				submitBtnText: ""
			},
			orderId: "",
			specSkuId: "",
			addressId: "",
			goodsList: null,
			maskState: 0, //优惠券面板显示状态
			showBatchBtn: false,
			orderInfo: {
				goodsList: []
			},

			addressData: {},
			baseFileUri
		};
	},

	computed: {
		...mapState("shop", ["shopDetailInfo"]),
		...mapState("afterSale", ["applicationRefundsData"])
	},

	onLoad(option) {
		console.log("option", option);
		this.orderId = option.orderId || "";
		// this.orderId = option.orderId || "2f8d56cb8a4d4fccb05b6095883208a4";
	},

	onShow() {
		this.getOrderDetail();
	},

	methods: {
		...mapMutations("afterSale", ["saveApplicationRefundsData"]),
		//  支付失败
		payFailAfter(){
			let routeLink = "/pages/user/pages/order/orderList";
			uni.reLaunch({ url: routeLink });
		},
		//  付款成功之后
		paySuccessAfter(){
			uni.redirectTo({
				url: "/pages/user/pages/order/orderList"
			});
		},
		// 点击--立即支付或确认收货
		onFullSubmit(){
			const status = this.orderInfo.status; // 100: 待付款 300: 确认收货
			const orderId = this.orderInfo.orderId;
			const orderType = this.orderInfo.type;  //
			/* 线上订单 */
			if(orderType=='10'){ 
				if (status === 100) {
					this.openPopPay();
				} else if (status === 300) {
					this.onConfirmReceipt(orderId);
				}
			/* 到店订单 */
			}else if(orderType=='15'){
				this.openPopPay();
			}
		},
		// 立即支付或确认收货
		async callPay(val,callback) {
			const status = this.orderInfo.status; // 100: 待付款 300: 确认收货
			const orderId = this.orderInfo.orderId;
			let payInfo;
			if (status === 100) {
				try {
					payInfo = await this.onPay(orderId,this.payMoneyType);
					//支付结果
					callback(payInfo);
				} catch (error) {
					console.log("error", error);
					//支付结果
					callback(payInfo);
					//this.$api.showToast("支付失败");
				}
			} else if (status === 300) {
				//this.onConfirmReceipt(orderId);
			}
		},

		async onCancelOrder(orderId) {
			try {
				await this.cancelOrder(orderId);
				await this.$api.showToast("成功取消");
				uni.redirectTo({ url: "/pages/user/pages/order/orderList" });
			} catch (error) {
				this.$api.showToast(error.resultInfo || "操作失败");
			}
		},

		async onConfirmReceipt(orderId) {
			try {
				await this.confirmReceipt(orderId);
				await this.$api.showToast("操作成功");
				uni.redirectTo({ url: "/pages/user/pages/order/orderList" });
			} catch (error) {
				console.log("error", error);
				this.$api.showToast(error.resultInfo || "操作失败");
			}
		},

		async onDeleteOrder(orderId) {
			try {
				await this.deleteOrder(orderId);
				await this.$api.showToast("成功删除");
				uni.redirectTo({ url: "/pages/user/pages/order/orderList" });
			} catch (error) {
				console.log("error", error);
				this.$api.showToast(error.resultInfo || "操作失败");
			}
		},

		// 显示批量退款按钮
		showBatchBtnFn() {
			const status = this.orderInfo.status;
			let isRefundsNum = 0;
			this.orderInfo.orderGoodsList.forEach((item, idnex) => {
				if (item.refundsStatus === 0) {
					isRefundsNum += 1;
				}
			});

			if (status !== 100 && status !== 500 && isRefundsNum > 1) {
				this.showBatchBtn = true;
			}
		},

		// 查询订单详情
		async getOrderDetail() {
			const propsData = {
				orderId: this.orderId
			};
			try {
				const res = await queryOrderDetail(propsData);
				console.log(res);
				res.data.totalFee = `${res.data.totalFee}`.split(".");
				// res.data.orderGoodsList.forEach((item, index) => {
				//   res.data.orderGoodsList[index].price = item.priceStr.split(".");
				// });

				// res.data.orderGoodsList = this.splitGoodsPrice(
				//   res.data.orderGoodsList,
				//   "price",
				//   "priceStr"
				// );

				this.orderInfo = res.data;
				this.viewFullSubmitText(this.orderInfo.status);
				this.showBatchBtnFn();
			} catch (error) {
				console.log("error", error);
				await this.$api.showToast(error.resultInfo || "操作失败");
				uni.navigateBack();
			}
			this.loaded = true;
		},

		// 主按钮文字
		viewFullSubmitText(status) {
			const orderType = this.orderInfo.type;
			let submitBtnText = "";
			if(orderType===10){
				if (status === 100) {
					submitBtnText = "立即付款";
				} else if (status === 300) {
					submitBtnText = "确认收货";
				}
			}else if(orderType===15){
				if (status === 250) {
					submitBtnText = "出示核销码";
				}
			}
			this.statusPrompt.submitBtnText = submitBtnText;
		},

		// 状态icon图标显示
		viewStatusIcon(status) {
			if (status === 100 || status === 200) {
				return "clock-full";
			} else {
				return "checkmark-hollow";
			}
		},

		// 查询地址
		// getDefaultAddress() {
		// 	const propsData = {
		// 		addressId: ''
		// 	}
		// 	return queryDefaultAddress().then(res => {
		// 		console.log('res', res);
		// 		this.addressData = res.data.model;
		// 	}).catch(error => {
		// 		console.log('error', error);
		// 	})
		// },

		// 单个退款
		separateRefunds(item) {
			const applicationRefundsData = {
				applied: false,
				orderId: this.orderInfo.orderId,
				isBatch: false,
				list: [
					{
						orderGoodsId: item.orderGoodsId,
						refundsNumber: item.buyNumber
					}
				]
			};
			this.saveApplicationRefundsData(applicationRefundsData);
			uni.navigateTo({ url: "/pages/user/pages/afterSale/refundsType" });
		},

		// 批量退款
		batchRefunds() {
			const orderId = this.orderInfo.orderId;
			const applicationRefundsData = {
				applied: false,
				isBatch: true,
				orderId,
				list: []
			};
			this.saveApplicationRefundsData(applicationRefundsData);
			uni.navigateTo({
				url: `/pages/user/pages/afterSale/refundsType`
			});
		},

		stopPrevent() {}
	}
};
</script>

<style lang="scss">
// 订单样式
@import "@/common/styles/order/orderDetail.scss";

.container {
	/* padding-top: 204rpx; */
	padding-top: 180rpx;
}

.price-section {
	margin-bottom: 120rpx;
}

/** 订单状态 */

.status-wrap {
	// position: absolute;
	position: fixed;
	top: 0;
	right: 0;
	left: 0;
	height: 180rpx;
	z-index: 95;
	.status-content {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		flex-direction: row;
		padding: 0 40rpx;
		.content {
			margin-left: 16rpx;
			.title {
				font-size: $theme-size-large-base;
			}
			.desc {
				font-size: 26rpx;
				margin-top: 20rpx;
			}
		}
	}
}

.footer {
	.btn-group {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		flex-direction: row;
		.btn {
			width: 184rpx;
		}
	}
}
</style>
